<?php

namespace Common\Service;
/**
 * 自定义session驱动
 * 不适用主从分离
 * Class SessionService
 * @package Common\Service
 */
class SessionService
{
    /**
     * Session有效时间
     */
    protected $lifeTime = '';

    private $db = false;

    /**
     * 打开Session
     * @access public
     * @param string $savePath
     * @param mixed $sessName
     */
    public function open($savePath, $sessName)
    {
        $this->db = D(C('SESSION_TABLE') ?: 'Session');
        $this->lifeTime = intval(C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') : ini_get('session.gc_maxlifetime'));
        return $this->db;
    }

    /**
     * 读取Session
     * @access public
     * @param string $sessID
     */
    public function read($sessID)
    {
        $map = array(
            'session_id' => $sessID,
            'session_expire' => array('gt', time()),
        );
        return $this->db->where($map)->getField('session_data');
    }

    /**
     * 关闭Session
     * @access public
     */
    public function close()
    {
        $this->gc($this->lifeTime);
        $this->db = null;
        return true;
    }

    /**
     * 写入session
     * @param $sessID
     * @param $sessData
     * @return mixed
     */
    public function write($sessID, $sessData)
    {
        $expire = time() + $this->lifeTime;
        $data = array(
            'session_id' => $sessID,
            'session_data' => $sessData,
            'session_expire' => $expire,
            'create_time' => time(),
            'ip' => get_client_ip(),
            'type' => C('SESSION_PREFIX'), // 利用前缀作为类型 以区分session类型
        );
        return $this->db->add($data, array(), true);
    }

    /**
     * 删除Session
     * @access public
     * @param string $sessID
     */
    public function destroy($sessID)
    {
        $map = array('session_id' => $sessID);
        return $this->db->where($map)->delete();
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     */
    public function gc($sessMaxLifeTime)
    {
        $map = array(
            'session_expire' => array('elt', time()),
        );
        return $this->db->where($map)->delete();
    }
}